﻿using Aspfm.Main;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace Aspfm.Main
{
    public class PageTool
    {
        public const char splitChar = '★';
        public static string GetWebBaseUrl()
        {
            //object BaseUrlObj = CacheHelper.GetCache("Aspfm.GetWebBaseUrl");
            //if (BaseUrlObj != null)
            //{
            //    return BaseUrlObj.ToString();
            //}
            //else
            //{
                if (System.Web.HttpContext.Current != null)
                {
                    string url = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
                    if (System.Web.HttpContext.Current.Request.ApplicationPath.Length > 1)
                    {
                        url += System.Web.HttpContext.Current.Request.ApplicationPath + "/";
                    }
                    else
                    {
                        url += "/";
                    }
                   // CacheHelper.SetCache("Aspfm.GetWebBaseUrl", url);
                    return url;
                }
           // }
            return "";
        }
        public static string GetAspfmConfig(string typename, string keystr)
        {
            DataSourceList dslist = ConfigTool.ReadConn();
            if (dslist != null && dslist.DataParamsList != null)
            {
                foreach (DataParams dp in dslist.DataParamsList)
                {
                    if (dp.Key == typename.Trim().ToUpper() && dp.paramslist != null)
                    {
                        foreach (DataParamsInfo dpi in dp.paramslist)
                        {
                            if (dpi.Key == keystr.Trim().ToUpper())
                            {
                                return dpi.KeyValue.Trim();
                            }
                        }
                    }
                }
            }
            return "";
        }
        public static string GetWebConfig(string keystr)
        {
            string str = System.Configuration.ConfigurationManager.AppSettings[keystr];
            if (string.IsNullOrEmpty(str))
                return "";
            return str;
        }
        public static string LinkFile(string file)
        {
            string cachefile = file;
            object LinkFileObj = CacheHelper.GetCache("Aspfm." + cachefile);
            if (LinkFileObj != null)
            {
                return LinkFileObj.ToString();
            }
            else
            {
                string strfile = BaseAshx.CurrentPath() + file;
                if (System.IO.File.Exists(strfile))
                {
                    string time = System.IO.File.GetLastWriteTime(strfile).ToString("yyyyMMddHHmmss");
                    file += "?v=" + time;

                    string fileurl = GetUrl(file);
                    CacheHelper.SetCache("Aspfm." + cachefile, fileurl, strfile);
                    return fileurl;
                }
                return GetUrl(file);
            }
        }
        public static UserIdentity GetCurrentUser()
        {
            return new UserIdentity();
        }
        public static string GetUrl(string url)
        {
            return GetWebBaseUrl() + url;
        }

        public static string GetAspxPage()
        {
            if (System.Web.HttpContext.Current != null)
            {
                if (System.Web.HttpContext.Current.Request.ApplicationPath.Length > 1)
                {
                    return System.Web.HttpContext.Current.Request.Url.AbsolutePath.Substring(System.Web.HttpContext.Current.Request.ApplicationPath.Length);
                }
                return System.Web.HttpContext.Current.Request.Url.AbsolutePath;
            }
            return "";
        }
        public static System.Diagnostics.Stopwatch GetAspxStartTime()
        {
            System.Diagnostics.Stopwatch swpage = new System.Diagnostics.Stopwatch();
            swpage.Start();
            return swpage;
        }
        public static string GetAspxLoadTime(System.Diagnostics.Stopwatch swpage)
        {
            if (swpage != null && swpage.IsRunning)
            {
                swpage.Stop();
                return "<!--耗时{" + swpage.ElapsedMilliseconds + "}毫秒-->";
            }
            return "";
        }
        public static string GetAspxParamsAll()
        {
            if (System.Web.HttpContext.Current != null)
            {
                if (string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.Url.Query))
                {
                    return "?1=1";
                }
                return System.Web.HttpContext.Current.Request.Url.Query;
            }
            return "";
        }
        public static string GetAspxParamsRemove(params string[] paramKey)
        {
            if (System.Web.HttpContext.Current != null)
            {
                if (paramKey != null)
                {
                    string pageParams = "?1=1";
                    foreach (string str in System.Web.HttpContext.Current.Request.QueryString.Keys)
                    {
                        if (!paramKey.Contains(str))
                        {
                            pageParams += "&" + str + "=" + System.Web.HttpContext.Current.Request.QueryString[str];
                        }
                    }
                    return pageParams;
                }
            }
            return GetAspxParamsAll();
        }

        public static string GetAspx(string aspx)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            string url = GetUrl(aspx);
            if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request != null && System.Web.HttpContext.Current.Request.Url != null)
            {
                if (url.Contains("?"))
                {
                    url += "&" + System.Web.HttpContext.Current.Request.Url.Query.TrimStart('?');
                }
                else
                {
                    url += System.Web.HttpContext.Current.Request.Url.Query;
                }
            }
            StringBuilder sbhtml = new StringBuilder("<!--开始URL:" + url + "-->");
            sbhtml.AppendLine();
            try
            {
                /*  winfrom调用接口示例
                  System.Net.WebClient client = new System.Net.WebClient();
                  System.Collections.Specialized.NameValueCollection list = new System.Collections.Specialized.NameValueCollection();
                  list.Add("fmparams.Dll", "Aspfm.Login");
                  list.Add("fmparams.Class", "Aspfm.Login.Login");
                  list.Add("fmparams.Active", "login");
                  ///http://localhost:8080/AspfmAshx.ashx?fmparams.Dll=Aspfm.Login&fmparams.Class=Aspfm.Login.Login&fmparams.Active=login
                  byte[] bytes = client.UploadValues("http://localhost:8080/AspfmAshx.ashx", list);
                  MessageBox.Show( System.Text.Encoding.UTF8.GetString(bytes)); 
                  */
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
                Stream respStream = httpResp.GetResponseStream();      //得到数据流，再把数据流转化为特定的数据（图片，文本。。。）
                //如果是图片流
                //pictureBox1.Image = Image.FromStream(respStream);
                //如果是文本流
                StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);  //编码为utf8
                sbhtml.AppendLine(respStreamReader.ReadToEnd());
            }
            catch (Exception ex)
            {
                sbhtml.AppendLine("错误URL:" + url + "\r\n错误信息:" + ex.Message);
            }
            sw.Stop();
            sbhtml.AppendLine("<!--结束URL:" + url + " {" + sw.ElapsedMilliseconds + "}毫秒-->");
            return sbhtml.ToString();
        }

        
        public static bool CheckLogin()
        {
            if (Thread.CurrentPrincipal != null &&
                        Thread.CurrentPrincipal.Identity != null &&
                        Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                return true;
            }
            else if (System.Web.HttpContext.Current!=null && System.Web.HttpContext.Current.Request.Cookies[SessionTool.CookieName] != null)
            {
                string cookies = System.Web.HttpContext.Current.Request.Cookies[SessionTool.CookieName].Value;
                return SessionTool.Longin(cookies);
            }
            return false;
        }
        /// <summary>
        /// 检查是否有访问站点权限。
        /// 可以自由定义过滤规则
        /// </summary>
        /// <returns></returns>
        public static bool CheckRole()
        {
            Aspfm.Main.UserIdentity user = new Aspfm.Main.UserIdentity();
            string url = System.Web.HttpContext.Current.Request.Url.LocalPath;
            AspfmRightModel AspfmRightAll = AspfmRight.XmlReaderAspfmRight();
            if (AspfmRightAll != null)
            {
                bool hadRight = true;
                foreach (string key in AspfmRightAll.paths.Keys)
                {
                    string path = "/" + key.Trim('/').Trim('\\') + "/";
                    if (url.StartsWith(path))
                    {
                        hadRight = false;
                        if (AspfmRightAll.paths[key].ToString() == "*")
                        {
                            hadRight = true;
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(user.SysRoleLevel))
                            {
                                string alllevel = "," + AspfmRightAll.paths[key].ToString() + ",";
                                string[] strlevels = user.SysRoleLevel.Split(',');
                                foreach (string str in strlevels)
                                {
                                    if (alllevel.Contains("," + str + ","))
                                    {
                                        hadRight = true;
                                    }
                                }
                            }
                        }
                    }
                }
                if (!hadRight)
                {
                    return hadRight;
                }
            }
            return true;
        }

        public static void BeginRequestLogin()
        {
            if (PageTool.CheckLogin()==false)
            {
                string strToken = System.Web.HttpContext.Current.Request.QueryString["AspfmToken"];
                if (!string.IsNullOrWhiteSpace(strToken))
                {
                    object objuser = CacheHelper.GetCache(strToken);
                    if (objuser != null && objuser is UserIdentity)
                    {
                        UserIdentity user = (UserIdentity)objuser;
                        SessionTool.Clear();
                        SessionTool.SetUserCookie(user);
                        CacheHelper.RemoveAllCache(strToken);

                        string returnurl = System.Web.HttpContext.Current.Request.QueryString["returnurl"];
                        if (!string.IsNullOrWhiteSpace(returnurl))
                        {
                            System.Web.HttpContext.Current.Response.Redirect(returnurl, false);
                        }
                    }
                }
            }
        }
    }
}
